package com.jzr.bedside.service.nettyUtils

import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Build
import android.os.IBinder
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.blankj.utilcode.utils.TimeUtils
import com.jzr.bedside.base.BaseApplication
import com.jzr.bedside.base.Constant
import com.jzr.bedside.utils.CommonUtil
import com.jzr.bedside.utils.PreferUtil
import com.jzr.netty.common.base.BaseMsg
import com.jzr.netty.common.base.MsgType
import com.jzr.netty.common.protocol.PingMsg
import com.orhanobut.logger.Logger
import io.netty.channel.ChannelFutureListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.concurrent.TimeUnit

class NettyService : Service() {

    private var receiver: NetworkReceiver? = null

    override fun onCreate() {
        super.onCreate()
        EventBus.getDefault().register(this)
        receiver = NetworkReceiver()
        val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver!!, filter)
        connect()
    }

    @Subscribe
    fun getEventBus(baseMsg: BaseMsg) {
        when (baseMsg.type) {
            MsgType.UPGRADE -> {
            }
        }
    }

    private fun connect() {
        BaseApplication.MAIN_EXECUTOR.submit {
            NettyClient.connect()
        }
        BaseApplication.MAIN_EXECUTOR.scheduleWithFixedDelay({
            NettyService.ping()
        }, 5, 1, TimeUnit.SECONDS)
    }

    companion object {
        fun ping() {
            val pingMsgData = PingMsg()
            pingMsgData.deptCode = PreferUtil.getInstance().deptCode
            pingMsgData.deviceIp = CommonUtil.getIP()
            pingMsgData.deviceMac = Build.SERIAL
            pingMsgData.lastUpTime = TimeUtils.getNowTimeDate()
            pingMsgData.type = MsgType.PING
            pingMsgData.deviceNo = Build.SERIAL
            pingMsgData.deviceType = 1

            NettyClient.sendMsgToServer(pingMsgData, ChannelFutureListener { future ->
                if (future?.isSuccess!!) {
                    Logger.e("Write heartbeat successful");
                } else {
                    Logger.e("Write heartbeat error");
                }
            })
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    inner class NetworkReceiver : BroadcastReceiver() {
        override fun onReceive(
            context: Context,
            intent: Intent
        ) {
            val cm =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetwork = cm.activeNetworkInfo
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.type == ConnectivityManager.TYPE_WIFI
                    || activeNetwork.type == ConnectivityManager.TYPE_MOBILE
                ) {
                    connect()
                }
            }
        }
    }

}